package com.example.mobifin_busticket;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import javax.mail.Message;
import javax.mail.Transport;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class SendMailMessage {
	static String responseMessage = "";

	private SendMailMessage() {
	}

	public static class SendMailTask extends AsyncTask<Message, Void, Void> {
		private Context mContext;
		private String moNO;
		private String strMessage;
		private String strEmail;
		private String[] strTagSplit;

		public SendMailTask(Context mContext, String strEmail, String moNO,
				String strMessage, String strTag) {
			this.mContext = mContext;
			this.moNO = moNO;
			this.strMessage = strMessage;
			this.strEmail = strEmail;
			this.strTagSplit = strTag.split(";");
			Log.d("strTagSplit", strTagSplit[0] + "--->" + strTagSplit[1]);
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			String[] pdTitleMsg, pdDestinationmsg;
			MyApplication.showProgressDialog(mContext, "Please wait..");
			// if (!isShowing && !MyApplication.getPd().isShowing()) {
			// if (pdMessage.contains("-")) {
			// pdTitleMsg = pdMessage.split(",");
			// pdDestinationmsg = pdTitleMsg[1].split("-");
			// MyApplication.showProgressDialog(mContext, pdTitleMsg[0]);
			// } else {
			// pdTitleMsg = pdMessage.split(",");
			// MyApplication.showProgressDialog(mContext, pdTitleMsg[0]);
			// }
			// }
		}

		@Override
		protected void onPostExecute(Void aVoid) {
			super.onPostExecute(aVoid);
			if (strTagSplit[0].equals(AppData.PRINTSCREEN)) {
				MyApplication.dismissProgressDialog();
			}
			if (isMyServiceRunning(mContext)) {
				mContext.stopService(new Intent(mContext,
						BgMailandSmsService.class));
			}
			if (strTagSplit[1].equals(AppData.EMAILID)) {
				if (responseMessage.contains("error")) {
					Toast toast = Toast.makeText(mContext, mContext
							.getResources().getString(R.string.SendMailFail),
							Toast.LENGTH_LONG);
					toast.show();
					responseMessage = "";
					MyApplication.dismissProgressDialog();
				} else {
					Toast toast = Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.SendMailSuccess),
							Toast.LENGTH_LONG);
					toast.show();
					responseMessage = "";
					Log.d("SendMail", "Success" + responseMessage);
					MyApplication.dismissProgressDialog();
				}

			} else if (strTagSplit[1].equals(AppData.SMSBODY)) {

				if (responseMessage.contains("error")) {
					Toast toast = Toast.makeText(mContext, mContext
							.getResources().getString(R.string.SendSmsFail),
							Toast.LENGTH_LONG);
					toast.show();
					responseMessage = "";
					MyApplication.dismissProgressDialog();
				} else {
					Toast toast = Toast.makeText(mContext, mContext
							.getResources().getString(R.string.SendSmsSuccess),
							Toast.LENGTH_LONG);
					toast.show();
					responseMessage = "";
					Log.d("SendSMS", "Success" + responseMessage);
					MyApplication.dismissProgressDialog();
				}
			}
			Log.d("SendMail and Message", "Response" + responseMessage);
		}

		@Override
		protected Void doInBackground(Message... messages) {
			try {
				if (strTagSplit[1].equals(AppData.EMAILID)) {
					Transport.send(messages[0]);
				} else if (strTagSplit[1].equals(AppData.SMSBODY)) {
					sendMessage(moNO, strMessage);
				} else {
					if (!strEmail.equals(AppData.BLANKSTRING)) {
						Transport.send(messages[0]);
					} else {
						Log.d(AppData.ERROR, "EmailId is Empty");
					}
					sendMessage(moNO, strMessage);
				}
			} catch (Exception e) {
				Log.d(AppData.ERROR, e.toString(), e);
				responseMessage = "error";
			}
			return null;
		}
	}
//pacho run kar
	public static boolean isMyServiceRunning(Context context) {
		ActivityManager manager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (BgMailandSmsService.class.getName().equals(
					service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	public static void sendMessage(String moNo, String strMsg) {
		try {
			URL sendUrl = new URL(AppData.MESSAGEURL);
			Log.d("Requested Params", AppData.MESSAGEURL + "-->" + moNo
					+ "--->" + strMsg + "--->" + AppData.LOGINID + "--->"
					+ AppData.LOGINPASSWORD + "--->" + AppData.SOURCENAMESMS);
			HttpURLConnection urlConnection = (HttpURLConnection) sendUrl
					.openConnection();
			urlConnection.setRequestMethod("POST");
			urlConnection.setDoInput(true);
			urlConnection.setDoOutput(true);
			urlConnection.setUseCaches(false);
			urlConnection.setUseCaches(false);
			DataOutputStream dataOutputStream = new DataOutputStream(
					urlConnection.getOutputStream());
			dataOutputStream.writeBytes("username="
					+ URLEncoder.encode(AppData.LOGINID, "UTF-8")
					+ "&password="
					+ URLEncoder.encode(AppData.LOGINPASSWORD, "UTF-8")
					+ "&type=" + URLEncoder.encode("0", "UTF-8") + "&dlr="
					+ URLEncoder.encode("1", "UTF-8") + "&destination="
					+ URLEncoder.encode(moNo, "UTF-8") + "&source="
					+ URLEncoder.encode(AppData.SOURCENAMESMS, "UTF-8")
					+ "&message=" + URLEncoder.encode(strMsg, "UTF-8"));
			dataOutputStream.flush();
			dataOutputStream.close();
			BufferedReader daBufferedReader = new BufferedReader(
					new InputStreamReader(urlConnection.getInputStream()));
			String strResponse = "", dataBuffer = "";
			while ((dataBuffer = daBufferedReader.readLine()) != null) {
				strResponse += dataBuffer;
			}
			dataOutputStream.close();
			if (strResponse.contains("1701")) {
				Log.d("Sms Sent SuccessFully", "" + strResponse.toString());
			} else {
				responseMessage = "error";
				Log.d("Sms Not Sent SuccessFully", "" + strResponse.toString());
			}
			Log.d("responseFrom Send Message", "" + strResponse.toString()
					+ "--->" + urlConnection.getResponseCode());
		} catch (Exception e) {
			Log.e(AppData.TAG, e.toString(), e);
			responseMessage = "error";
		}
	}
}
